package com.example.yichuangyun.utils;

import com.example.yichuangyun.utils.sharedpreference.SPUtil;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import java.util.Iterator;
import java.util.List;

public class SearchHistoryUtil {

    /**
     * 保存搜索记录到本地
     *
     * @param keyWord 搜索关键字
     */
    public static void saveKeyWord(String keyWord) {
        String json = SPUtil.getString("history", "[]");
        JsonArray jsonArray = new JsonParser().parse(json).getAsJsonArray();
        Gson gson = new Gson();
        List<String> list = gson.fromJson(jsonArray, new TypeToken<List<String>>() {
        }.getType());
        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            String str = iterator.next();
            if (keyWord.equals(str)) {
                iterator.remove();
            }
        }
        list.add(0, keyWord);
        if (list.size() > 10) {
            list.remove(list.size() - 1);
        }
        SPUtil.put("history", new Gson().toJson(list));
    }

    /**
     * 获取本地搜索记录
     *
     * @return list
     */
    public static List<String> getHistory() {
        String history = SPUtil.getString("history", "[]");
        JsonArray jsonArray = new JsonParser().parse(history).getAsJsonArray();
        Gson gson = new Gson();
        return gson.fromJson(jsonArray, new TypeToken<List<String>>() {
        }.getType());
    }

    /**
     * 清空搜索记录
     */
    public static void cleanHistory() {
        SPUtil.put("history", "[]");
    }
}
